package com.tangtang.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tangtang.common.constant.ProductConstant;
import com.tangtang.gulimall.product.Vo.AtrrVo;
import com.tangtang.gulimall.product.Vo.AttrGroupRelationVo;
import com.tangtang.gulimall.product.Vo.AttrRespVo;
import com.tangtang.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.tangtang.gulimall.product.dao.AttrGroupDao;
import com.tangtang.gulimall.product.dao.CategoryDao;
import com.tangtang.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.tangtang.gulimall.product.entity.AttrGroupEntity;
import com.tangtang.gulimall.product.entity.CategoryEntity;
import com.tangtang.gulimall.product.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangtang.common.utils.PageUtils;
import com.tangtang.common.utils.Query;

import com.tangtang.gulimall.product.dao.AttrDao;
import com.tangtang.gulimall.product.entity.AttrEntity;
import com.tangtang.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    //查询分组名称
    @Resource
    private AttrGroupDao attrGroupDao;

    //查询一个分类的名称
    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryService categoryService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AtrrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //第一种保存方式（麻烦）
        /*attrEntity.setAttrName(attr.getAttrName());
        attrEntity.setSearchType(attr.getSearchType());
        attrEntity.setIcon(attr.getIcon());
        attrEntity.setValueSelect(attr.getValueSelect());
        attrEntity.setAttrType(attr.getAttrType());
        attrEntity.setEnable(attr.getEnable());
        attrEntity.setCatelogId(attr.getCatelogId());
        attrEntity.setShowDesc(attr.getShowDesc());*/
        //第二种保存方式(这个是spring提供的属性复制，第一个是属性源，第二个是将属性源复制到的位置)
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);

        //保存关联关系
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
        attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
    }

    /**
     * 这里面，分两步
     * 一：查询
     * 二：将查询到的属性返回给页面以及返回给AttrRespVo
     * @param params
     * @param categoryid
     * @return
     */
    @Override
    public PageUtils queryAttrbase(Map<String, Object> params, Long categoryid) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        //如果categoryid等于0并且key也为空，则查询全部
        if (categoryid != 0) {
            queryWrapper.eq("catelog_id",categoryid);
        }

        if (!StringUtils.isEmpty(key)) {
            //如果cateid不为0，和key都不为空，则进行条件查询
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryWrapper.and((wrapper) -> {
                        wrapper.eq("attr_id", key).or().like("attr_name", key);
                    })
            );
            return new PageUtils(page);
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        //这里可以作为一个重点参考
        //这里还得将AttrVo的属性返回给AttrRepVo
        //这里用了当前分页的记录列表
        /*PageUtils pageUtils = new PageUtils(page);
        //这个是纪录list分页表中的情况
        List<AttrEntity> listrecords = page.getRecords();
        //用流的写法来遍历的。
        //需要定义一个AttrRespVo返回的参数
        List<AttrRespVo> respVos = listrecords.stream().map((attrEntity)->{
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity,attrRespVo);
            //查询分类id的名称
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if(categoryEntity!=null){
                System.out.println("返回的结果为："+categoryEntity.toString());
                attrRespVo.setName(categoryEntity.getName());
            }
            //查询分组名称
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
            if(attrAttrgroupRelationEntity!=null)
            {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                System.out.println(attrGroupEntity.toString());
                attrRespVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());*/
        //使用正常的写法添加
        PageUtils pageUtils = new PageUtils(page);
        //获取分页纪录
        List<AttrEntity> listrecords = page.getRecords();
        //获取所有AttrRespVo的参数
        List<AttrRespVo> respVos = new ArrayList<AttrRespVo>();
        for (AttrEntity attrEntity:listrecords) {
            //得判断是否是规格属性
            if(attrEntity.getAttrType()==ProductConstant.Attrenum.ATTR_TYPE_BASE.getCode())
            {
                AttrRespVo attrRespVo = new AttrRespVo();
                //将属性参数值复制
                BeanUtils.copyProperties(attrEntity,attrRespVo);
                //根据分类id查询名称
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                if(categoryEntity!=null)
                {
                    attrRespVo.setName(categoryEntity.getName());
                }
                //根据分组id查询分组名称（如果有多条报错）,attr_id必须保证唯一性，如果绑定多条属就会报错
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId())
                );
                if (attrAttrgroupRelationEntity != null){
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                        attrRespVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                }
                //如果是多条
                /*List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = attrAttrgroupRelationDao.selectList(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId())
                );
                for (AttrAttrgroupRelationEntity attrAttrgroupRelationEntity:attrAttrgroupRelationEntityList) {
                    if (attrAttrgroupRelationEntity != null){
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                        attrRespVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }*/
                respVos.add(attrRespVo);
            }
        }
        pageUtils.setList(respVos);
        return pageUtils;
    }

    /**
     * 这里得查询方式跟base的查询方式一样
     * @param params
     * @param categoryid
     * @return
     */
    @Override
    public PageUtils queryAttrsale(Map<String, Object> params, Long categoryid) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        //如果categoryid等于0并且key也为空，则查询全部
        if (categoryid != 0) {
            queryWrapper.eq("catelog_id",categoryid);
        }

        if (!StringUtils.isEmpty(key)) {
            //如果cateid不为0，和key都不为空，则进行条件查询
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryWrapper.and((wrapper) -> {
                        wrapper.eq("attr_id", key).or().like("attr_name", key);
                    })
            );
            return new PageUtils(page);
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        //使用正常的写法添加
        PageUtils pageUtils = new PageUtils(page);
        //获取分页纪录
        List<AttrEntity> listrecords = page.getRecords();
        //获取所有AttrRespVo的参数
        List<AttrRespVo> respVos = new ArrayList<AttrRespVo>();
        for (AttrEntity attrEntity:listrecords) {
            //得判断是否是规格属性
            if(attrEntity.getAttrType()==ProductConstant.Attrenum.ATTR_TYPE_SALE.getCode())
            {
                AttrRespVo attrRespVo = new AttrRespVo();
                //将属性参数值复制
                BeanUtils.copyProperties(attrEntity,attrRespVo);
                //根据分类id查询名称
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                if(categoryEntity!=null)
                {
                    attrRespVo.setName(categoryEntity.getName());
                }
                //根据分组id查询分组名称
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId())
                );
                if (attrAttrgroupRelationEntity != null){
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    attrRespVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                }
                respVos.add(attrRespVo);
            }
        }
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo respVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,respVo);
        //通过分类id来查询相应的信息
        Long[] path = categoryService.findCatelogpath(attrEntity.getCatelogId());
        respVo.setCatelogPath(path);
        //通过中间表来查询相应的分组id
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
        respVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
        //根据id查询相应的名称
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
        respVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());

        return respVo;
    }

    /**
     * 更新AttrEntity的实体数据
     * 这里面主要更新两个数据
     * 一个attr表的数据，
     * 一个是attr_attrgroup_renalition中间表的attr_group_id的数据
     * @param attr
     */
    @Override
    public void updateAttr(AttrRespVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //将参数值传入attrEntity的实体类
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        //修改规格属性
        if(attr.getAttrType()== ProductConstant.Attrenum.ATTR_TYPE_BASE.getCode())
        {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());

            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<AttrAttrgroupRelationEntity>();
            queryWrapper.eq("attr_id",attr.getAttrId());
            //进行查询统计,如果统计的参数大于0，则进行更新
            Integer count = attrAttrgroupRelationDao.selectCount(queryWrapper);
            if (count>0){
                //这一块将attr_id的参数全部更新了最后一次更新的参数
                UpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new UpdateWrapper<AttrAttrgroupRelationEntity>();
                updateWrapper.eq("attr_id",attr.getAttrId());
                //中间表全部进行了更新
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,updateWrapper);
            }else {
                //如果统计的不存在就进行新增
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }

    }

    /**
     * 商品分组回显
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //根据分组id将查询中间表对应的所有属性id
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId)
        );
        //将根据中间表查询的属性id存入一个List集合中
        List<Long> attr_ids = new ArrayList<Long>();
        for (AttrAttrgroupRelationEntity attrAttrgroupRelationEntity:attrAttrgroupRelationEntityList) {
            attr_ids.add(attrAttrgroupRelationEntity.getAttrId());
        }
        if (attr_ids == null || attr_ids.size()==0){
            return null;
        }
        //根据集合查询
        List<AttrEntity> attrEntities = this.listByIds(attr_ids);
        return attrEntities;

        //这是视频中的流式编写给值写法
        /*List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;*/
    }

    //进行分组关联删除
    @Override
    public void deleteattrgroup(AttrGroupRelationVo[] vos) {
        //查询中间表,流式遍历的写法Arrays.asList(vos)
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = new ArrayList<AttrAttrgroupRelationEntity>();
        //先将传过来的数组进行遍历
        for (AttrGroupRelationVo attrGroupRelationVo:vos) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrGroupRelationVo.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrGroupRelationVo.getAttrGroupId());

            attrAttrgroupRelationEntityList.add(attrAttrgroupRelationEntity);
        }
        //创建删除的方式
        attrAttrgroupRelationDao.deleteBatchRelation(attrAttrgroupRelationEntityList);
    }

    /**
     * 这里其实就是一个巨大的sql语句
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getnoatterelation(Map<String, Object> params, Long attrgroupId) {
        //根据attrgroupid获取对应的分组数据
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //获取分类id
        Long catelogid = attrGroupEntity.getCatelogId();
        //根据分类id获取相对应的分组id
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogid)
        );
        //将查询到的分组id,存入一个long的集合中
        List<Long> attrgroupids = new ArrayList<Long>();
        for (AttrGroupEntity attrGroupid:attrGroupEntities) {
            attrgroupids.add(attrGroupid.getAttrGroupId());
        }

        //根据attrgroupid查询比对中间表相对应的attrid是否在attrgroupids中
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",attrgroupids)
        );
        //将查询的attr_id放入到一个list
        List<Long> attrids = new ArrayList<>();
        for (AttrAttrgroupRelationEntity attrAttrgroupRelationEntity:attrAttrgroupRelationEntities) {
            attrids.add(attrAttrgroupRelationEntity.getAttrId());
        }

        //根据catelogid进行属性查询
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catelog_id",catelogid);

        //踢出已经存在的id
        if(attrids != null && attrids.size()>0)
        {
            queryWrapper.notIn("attr_id",attrids);
        }

        //params主要做搜索用的
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().eq("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }
}